package ch.ffhs.ks.mail;

import java.util.List;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Session;
import javax.mail.Store;
import javax.swing.SwingWorker;

import ch.ffhs.ks.model.Account;
import ch.ffhs.ks.model.ModelContext;

public class AccountInformationDownloader extends SwingWorker<Folder, Folder> {

	private Account account;
	private ModelContext modelContext;

	public AccountInformationDownloader(Account account, ModelContext modelContext)
	{
		this.account = account;

		this.modelContext = modelContext;

		this.modelContext.notifyProgress("Aktualisiere IMAP-Ordner");
	}


	@Override
	protected Folder doInBackground() throws Exception {

		Properties props = System.getProperties();
		props.setProperty("mail.store.protocol", "imaps");

		Session session = Session.getDefaultInstance(props, null);

		Store store = session.getStore("imaps");

		store.connect(account.getImapAddress(), 
				account.getEmailAddress(), 
				account.getPassword());

		for(Folder f : store.getDefaultFolder().list())
		{
			publish(f);
		}

		return null;

	}

	@Override
	protected void done() {
		super.done();
		
		modelContext.buildTree();
		modelContext.notifyProgress("IMAP-Ordner aktualisiert");
	}

	@Override
	protected void process(List<Folder> chunks) {

		for(Folder c : chunks)
		{
			ch.ffhs.ks.model.Folder f = new ch.ffhs.ks.model.Folder(account, c.getName(), true, null);

			account.addFolder(f);
		}

	}

}
